package com.kuang.example;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.net.URLEncoder;

public class cookies02 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       req.setCharacterEncoding("utf-8");
       resp.setCharacterEncoding("utf-8");
       resp.setContentType("text/html;charset=utf-8");
        PrintWriter out = resp.getWriter();
        Cookie[] cookies = req.getCookies();
        if(cookies!=null){
            out.write("登录用户名为：");
            for (int i = 0; i < cookies.length; i++) {
                Cookie cookie=cookies[i];
                if("username".equals(cookie.getName())){
                    String value = cookie.getValue();
                    out.write(URLDecoder.decode(value,"UTF-8"));
                }

            }
        }else {
            out.println("用户没有登录！");
        }

        Cookie cookie = new Cookie("username", URLEncoder.encode("汪小平","UTF-8"));
        cookie.setMaxAge(24*60*60);
        resp.addCookie(cookie);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
